namespace RuoVea.OmiApi.SystemApp.Service;

/// <summary>
/// 系统职位服务 🔷
/// </summary>
[ApiExplorerSettings(GroupName = "system")]
public class SysPosService : IApplicationService
{
    private readonly ICurrentUser _currentUser;
    private readonly SugarRepository<SysPosition> _sysPosRep;
    private readonly SysUserExtOrgService _sysUserExtOrgService;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="currentUser"></param>
    /// <param name="sysPosRep"></param>
    /// <param name="sysUserExtOrgService"></param>
    public SysPosService(ICurrentUser currentUser,
        SugarRepository<SysPosition> sysPosRep,
        SysUserExtOrgService sysUserExtOrgService)
    {
        _currentUser = currentUser;
        _sysPosRep = sysPosRep;
        _sysUserExtOrgService = sysUserExtOrgService;
    }

    /// <summary>
    /// 获取职位列表 🔹
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取职位列表")]
    public async Task<List<SysPosition>> GetList([FromQuery] PosInput input)
    {
        return await _sysPosRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code))
            .OrderBy(u => new { u.Sort, u.Id })
            .Mapper(u =>
            {
                u.UserList = _sysPosRep.Context.Queryable<SysUser>()
                    .Where(a => SqlFunc.Subqueryable<SysUserExtOrg>()
                        .Where(t => a.Id == t.UserId && t.PosId == u.Id).Any())
                    .ToList();
            })
            .ToListAsync();
    }

    /// <summary>
    /// 增加职位 🔹
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [DisplayName("增加职位")]
    public async Task AddPos(AddPosInput input)
    {
        if (await _sysPosRep.IsAnyAsync(u => u.Name == input.Name && u.Code == input.Code))
            throw  new ArgumentException(i18n.position_exists);

        await _sysPosRep.InsertAsync(input.Adapt<SysPosition>());
    }

    /// <summary>
    /// 更新职位 🔹
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPut]
    [DisplayName("更新职位")]
    public async Task UpdatePos(UpdatePosInput input)
    {
        if (await _sysPosRep.IsAnyAsync(u => u.Name == input.Name && u.Code == input.Code && u.Id != input.Id))
            throw  new ArgumentException(i18n.position_exists);

        var SysPosition = await _sysPosRep.GetByIdAsync(input.Id) ?? throw  new ArgumentException(i18n.position_not_exists);
        if (!_currentUser.IsSuperAdmin && SysPosition.Creator != _currentUser.UserId)
            throw  new ArgumentException(i18n.no_permission_to_modify_position);

        await _sysPosRep.AsUpdateable(input.Adapt<SysPosition>()).IgnoreColumns(true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除职位 🔹
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpDelete]
    [DisplayName("删除职位")]
    public async Task DeletePos([FromBody] DeletePosInput input)
    {
        var SysPosition = await _sysPosRep.GetFirstAsync(u => u.Id == input.Id) ?? throw  new ArgumentException(i18n.position_not_exists);
        if (!_currentUser.IsSuperAdmin && SysPosition.Creator != _currentUser.UserId)
            throw  new ArgumentException(i18n.no_permission_to_modify_position);

        // 若职位有用户则禁止删除
        var hasPosEmp = await _sysPosRep.ChangeRepository<SugarRepository<SysUserExtOrg>>()
            .IsAnyAsync(u => u.PosId == input.Id);
        if (hasPosEmp)
            throw  new ArgumentException(i18n.position_has_users);

        // 若附属职位有用户则禁止删除
        var hasExtPosEmp = await _sysUserExtOrgService.HasUserPos(input.Id);
        if (hasExtPosEmp)
            throw  new ArgumentException(i18n.position_has_users);

        await _sysPosRep.DeleteAsync(u => u.Id == input.Id);
    }
}